/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.consumer.controller;

import com.lvyh.lightframe.core.config.ReferenceConfig;
import com.lvyh.lightframe.core.generic.GenericService;
import com.lvyh.lightframe.core.util.GenericObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * Generic invoke
 * <p>
 * http://localhost:8081/generic-service
 */
@Controller
public class GenericController {
    private Logger logger = LoggerFactory.getLogger(GenericController.class);

    @RequestMapping("generic-service")
    @ResponseBody
    public Object genericService() throws Exception {

        String requestClassName = "com.lvyh.lightframe.provider.dto.UserInfoRequest";
        String className = "com.lvyh.lightframe.provider.service.BossUserService";
        String methodName = "getUserInfo";
        Object responseObj = null;

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", 1000);
        paramMap.put("userName", "xiaozhang");
        Object genericObject = GenericObjectUtil.buildGenericObject(requestClassName, paramMap);

        // Reference a service
        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<GenericService>().setInterfaceId(className).setGeneric(true);

        // Get the agent class
        GenericService genericService = referenceConfig.refer();

        logger.info("proxy genericService:{}", genericService);

        responseObj = genericService.$invoke(methodName, new String[]{requestClassName}, new Object[]{genericObject});

        logger.info("[GenericController] rpc invoke result:{}", responseObj);

        return responseObj;
    }
}
